package com.hwadee.property.util;

import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.UUID;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 捕获自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult handleBusinessException(BusinessException e) {
        logger.error("BusinessException (Request ID: {}): {}", getRequestId(), e.getMessage(), e);
        return AjaxResult.error(e.getCode(), "【业务异常】" + e.getMessage(), getRequestId());
    }

    // 捕获其他异常
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        logger.error("Exception (Request ID: {}): {}", getRequestId(), e.getMessage(), e);
        return AjaxResult.error(ErrorCodes.SERVER_ERROR, "【服务器异常】", getRequestId());
    }

    // 捕获 JwtException
    @ExceptionHandler(JwtException.class)
    public AjaxResult handleJwtException(JwtException e) {
        logger.error("JwtException (Request ID: {}): {}", getRequestId(), e.getMessage(), e);
        return AjaxResult.error(ErrorCodes.FORBIDDEN, "【权限错误】" + e.getMessage(), getRequestId());
    }

    // 捕获参数校验异常
    @ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class)
    public AjaxResult handleValidationException(org.springframework.web.bind.MethodArgumentNotValidException e) {
        logger.error("ValidationException (Request ID: {}): {}", getRequestId(), e.getBindingResult().getFieldError().getDefaultMessage(), e);
        return AjaxResult.error(ErrorCodes.INVALID_INPUT, "【参数校验异常】" + e.getBindingResult().getFieldError().getDefaultMessage(), getRequestId());
    }

    // 捕获 IllegalArgumentException
    @ExceptionHandler(IllegalArgumentException.class)
    public AjaxResult handleIllegalArgumentException(IllegalArgumentException e) {
        logger.error("IllegalArgumentException (Request ID: {}): {}", getRequestId(), e.getMessage(), e);
        return AjaxResult.error(ErrorCodes.INVALID_INPUT, "【非法参数异常】" + e.getMessage(), getRequestId());
    }

    private String getRequestId() {
        return UUID.randomUUID().toString(); // 或从请求头中获取
    }
}
